package com.jcgyl.export.websocket;

import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class ProcessWebSocketHandler extends TextWebSocketHandler {
	private static Logger logger = LoggerFactory.getLogger(ProcessWebSocketHandler.class);
	private static CopyOnWriteArraySet<WebSocketSession> sessions = new CopyOnWriteArraySet<WebSocketSession>();

	public ProcessWebSocketHandler() {
	}

	@Override
	public void afterConnectionEstablished(WebSocketSession session) {
		logger.debug("Opened new session in instance " + this);
		sessions.add(session);
		System.out.println("Open new session in instance");
	}

	@Override
	public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		String echoMessage = message.getPayload();
		logger.debug(echoMessage);
		session.sendMessage(new TextMessage(echoMessage));
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		session.close(CloseStatus.SERVER_ERROR);
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		sessions.remove(session);
	}

	public static void sendInfo(String message) throws IOException {
		Iterator<WebSocketSession> iterators = sessions.iterator();
		while (iterators.hasNext()) {
			WebSocketSession session = iterators.next();
			session.sendMessage(new TextMessage(message));
		}
	}

}
